package com.hins.stack;

public class Calculator {
    public static void main(String[] args) throws Exception {
        String expression = "7010*200*2-5+1-5+3-4";

        ArraryStackDemo.ArrayStack numStack = new ArraryStackDemo.ArrayStack(10);
        ArraryStackDemo.ArrayStack operStack = new ArraryStackDemo.ArrayStack(10);

        int index = 0;
        char c;
        String keepNum = "";

        while (true) {
            c = expression.substring(index, index + 1).charAt(0);

            if (operStack.isOper(c)) {
                if (operStack.isEmpty()) {
                    operStack.push(c);
                } else {
                    //如果符号栈有操作符，就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符,就需要从数栈中pop出两个数,
                    //在从符号栈中pop出一个符号，进行运算，将得到结果，入数栈，然后将当前的操作符入符号栈
                    if (operStack.priority(c) <= operStack.priority(operStack.peek())) {
                        int num1 = numStack.pop();
                        int num2 = numStack.pop();
                        int oper = operStack.pop();
                        int cal = numStack.cal(num1, num2, oper);
                        numStack.push(cal);
                        operStack.push(c);
                    }
                }
            } else {

                 keepNum += c;

                 if (index == expression.length() - 1) {
                     numStack.push(Integer.valueOf(keepNum));
                 } else {
                     if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {
                         //如果后一位是运算符，则入栈 keepNum = "1" 或者 "123"
                         numStack.push(Integer.parseInt(keepNum));
                         //重要的!!!!!!, keepNum清空
                         keepNum = "";
                     }
                 }


            }

            index++;
            if (index >= expression.length()) {
                break;
            }
        }

        //当表达式扫描完毕，就顺序的从 数栈和符号栈中pop出相应的数和符号，并运行.
        while(true) {
            //如果符号栈为空，则计算到最后的结果, 数栈中只有一个数字【结果】
            if(operStack.isEmpty()) {
                break;
            }
            int num1 = numStack.pop();
            int num2 = numStack.pop();
            int oper = operStack.pop();
            int res = numStack.cal(num1, num2, oper);
            numStack.push(res);//入栈
        }
        //将数栈的最后数，pop出，就是结果
        int res2 = numStack.pop();
        System.out.printf("表达式 %s = %d", expression, res2);
    }

}
